package com.partition.mysql.task;

import com.partition.mysql.bean.PartitionItem;
import com.partition.mysql.config.PartitionConfig;
import com.partition.mysql.em.RangeStrategyEnum;
import com.partition.mysql.handle.CompositePartitionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时创建清理分区任务
 *
 * @author hexinglin
 * @created 2022-04-13 10:15
 **/
@Configuration     //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class SaticScheduleTask {
    private static final Logger logger = LoggerFactory.getLogger(SaticScheduleTask.class);
    /**
     * 应用配置文件
     */
    @Autowired
    private PartitionConfig partitionConfig;

    /**
     * 处理策略
     */
    @Autowired
    private CompositePartitionHandler compositePartitionHandler;



    //3.添加定时任务
    @Scheduled(cron = "${partition.config.cron}")
    private void configureTasks() {

        Boolean partitionOnStartup = partitionConfig.getPartitionEnable();
        List<PartitionItem> partItems = partitionConfig.getPartItems();

        if (!partitionOnStartup|| CollectionUtils.isEmpty(partItems)){
            //没有开启表分区或没有配置定时分区表，不执行定时任务
            return;
        }

        logger.info("-------------开始执行表分区定时任务----------------");
        partitionJob(partItems);
        logger.info("-------------完成执行表分区定时任务----------------");

    }


    /*
    * 表分区方法
    */
    private void partitionJob( List<PartitionItem> partItems){
        for (PartitionItem partItem : partItems) {
            compositePartitionHandler.partitionJob(partItem, RangeStrategyEnum.getByCode(partItem.getRangeStrategy()));
        }
    }

}
